﻿// WebZHX.Infrastructure/Services/BaseService.cs
using Common.Models;
using Core.Interfaces;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Infrastructure.Services
{
    /// <summary>
    /// 基础服务
    /// </summary>
    /// <typeparam name="TEntity">实体类型</typeparam>
    /// <typeparam name="TKey">主键类型</typeparam>
    public class BaseService<TEntity, TKey> where TEntity : class, IEntity<TKey>
    {
        protected readonly IBaseRepository<TEntity, TKey> _repository;
        protected readonly IPagedRepository<TEntity, TKey> _pagedRepository;

        public BaseService(IBaseRepository<TEntity, TKey> repository, IPagedRepository<TEntity, TKey> pagedRepository)
        {
            _repository = repository;
            _pagedRepository = pagedRepository;
        }

        /// <summary>
        /// 根据主键获取实体
        /// </summary>
        public virtual async Task<TEntity> GetByIdAsync(TKey id)
        {
            return await _repository.GetByIdAsync(id);
        }

        /// <summary>
        /// 获取所有实体
        /// </summary>
        public virtual async Task<IEnumerable<TEntity>> GetAllAsync()
        {
            return await _repository.GetAllAsync();
        }

        /// <summary>
        /// 新增实体
        /// </summary>
        public virtual async Task<TEntity> CreateAsync(TEntity entity)
        {
            return await _repository.AddAsync(entity);
        }

        /// <summary>
        /// 更新实体
        /// </summary>
        public virtual async Task<TEntity> UpdateAsync(TEntity entity)
        {
            return await _repository.UpdateAsync(entity);
        }

        /// <summary>
        /// 局部更新实体（只更新非null字段）
        /// </summary>
        public virtual async Task<TEntity> PartialUpdateAsync(TEntity entity)
        {
            return await _repository.PartialUpdateAsync(entity);
        }

        /// <summary>
        /// 删除实体
        /// </summary>
        public virtual async Task<bool> DeleteAsync(TKey id)
        {
            return await _repository.DeleteAsync(id);
        }

        /// <summary>
        /// 软删除实体
        /// </summary>
        public virtual async Task<bool> SoftDeleteAsync(TKey id)
        {
            return await _repository.SoftDeleteAsync(id);
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        public virtual async Task<PagedResult<TEntity>> GetPagedAsync(int pageIndex, int pageSize, string orderBy = "Id")
        {
            return await _pagedRepository.GetPagedAsync(pageIndex, pageSize, orderBy);
        }

        /// <summary>
        /// 分页查询（带过滤条件）
        /// </summary>
        public virtual async Task<PagedResult<TEntity>> GetPagedAsync(QueryFilter filter)
        {
            return await _pagedRepository.GetPagedAsync(filter);
        }
    }
}